package cn.tb.ymcc.mq.listener;

import cn.tb.ymcc.domain.PayOrder;
import cn.tb.ymcc.dto.PayNotifyDto;
import cn.tb.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(
        txProducerGroup = "service-pay-tx-group"
)
public class PayNotifyRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;
    @Autowired

    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //保存本地事务，修改支付单的状态和时间
        PayOrder payOrder = (PayOrder)o;
        PayOrder orderTmp = payOrderService.selectByOrderNo(payOrder.getOrderNo());
        //支付单状态不是待支付，回滚
        if(orderTmp.getPayStatus().intValue()!=PayOrder.STATE_WAIT_PAY.intValue()){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        payOrderService.updateById(payOrder);
        return RocketMQLocalTransactionState.COMMIT;

    }

    /**
     * 检查本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] body = (byte[]) message.getPayload();
            String notifyDtoStr  = new String(body, StandardCharsets.UTF_8);
            PayNotifyDto payNotifyDto = JSONObject.parseObject(notifyDtoStr, PayNotifyDto.class);
            if(payNotifyDto==null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            PayOrder payOrder = payOrderService.selectByOrderNo(payNotifyDto.getOrderNo());
            if(payOrder==null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            //判断支付单的状态
            if(payOrder.getPayStatus() == PayOrder.STATE_PAY_SUCCESS){
                return RocketMQLocalTransactionState.COMMIT;
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
